<script lang="ts" setup>
    import { ref, onMounted, computed } from 'vue'
    import {
        Check,
        Delete,
        Edit,
        Message,
        Search,
        Star,
    } from '@element-plus/icons-vue';
    import type { ComponentSize } from 'element-plus';
    import * as Article from '@/api/article.js';
    import { reactive } from 'vue';

    // 定义选项
    const categoryList = ref([]);
    const stateList = ref([]);

    // 获取文章分类列表
    const fetchCategoryList = async () => {
        // 调用后端接口获取文章分类列表
        const data = await Article.selectAllCategory();
        categoryList.value = data;

    }

    // 生成分类选项
    const categoryOptions = computed(() => [
        { label: '全部分类', value: '' }, // 默认“全部”选项
        ...categoryList.value.map(category => ({
            label: category.categoryName,
            value: category.id
        }))
    ]);

    // 获取文章状态列表
    const fetchStateList = async () => {
        // 调用后端接口获取文章状态列表
        const data = await Article.selectAllState();
        stateList.value = data;

    }

    // 生成状态选项
    const stateOptions = computed(() => [
        { label: '全部状态', value: '' }, // 默认“全部”选项
        ...stateList.value.map(state => ({
            label: state.stateName,
            value: state.id
        }))
    ]);

    const formInline = reactive({
        keyword: '',     // 搜索关键字
        categoryId: '',  // 分类ID（对应后端的categoryId）
        stateId: '',     // 状态ID（对应后端的stateId）
        date: ''         // 发布时间
    })

    const onSubmit = async () => {
        console.log('搜索条件:', formInline);
        currentPage.value = 1; // 搜索时重置为第一页
        fetchAllArticles(); // 执行搜索
    }

    // 分页相关数据
    const currentPage = ref(1) // 当前页码
    const pageSize = ref(5) // 每页条数
    const total = ref(0) // 总条数
    const size = ref < ComponentSize > ('default') // 分页组件大小
    const background = ref(false) // 是否显示背景色
    const disabled = ref(false) // 是否禁用分页组件

    // 监听分页变化 - 每页条数改变
    const handleSizeChange = (val: number) => {
        console.log(`每页 ${val} 条`);
        pageSize.value = val;
        currentPage.value = 1; // 重置为第一页
        fetchAllArticles(); // 重新加载数据
    }

    // 监听分页变化 - 当前页码改变
    const handleCurrentChange = (val: number) => {
        console.log(`当前页: ${val}`);
        currentPage.value = val;
        fetchAllArticles(); // 重新加载数据
    }

    // 表格数据（响应式，初始为空数组）
    const tableData = ref([])

    // 页面初始化时加载数据
    onMounted(() => {
        // 初始加载所有文章
        fetchCategoryList(); // 加载分类
        fetchStateList();    // 加载状态
        fetchAllArticles();  // 加载文章
    })

    // 获取所有文章列表
    const fetchAllArticles = async () => {
        const data = await Article.selectAllArticle({
            pageNum: currentPage.value,         // 当前页码
            pageSize: pageSize.value,           // 分页参数
            categoryId: formInline.categoryId,  // 分类筛选
            stateId: formInline.stateId,        // 状态筛选
            // publishTime: formInline.date ? formInline.date.toISOString() : null, // 发布时间筛选
        });
        tableData.value = data.list;
        total.value = data.total;
    }

    // 实现重置功能
    const onReset = () => {
        // 重置表单
        formInline.keyword = '';
        formInline.categoryId = null;
        formInline.stateId = null;
        formInline.date = null;

        // 重新加载数据
        currentPage.value = 1;
        fetchAllArticles();
    }
</script>

<template>
    <div class="table-container">
        <el-card style="max-width: 100%">
            <div class="card-header">
                <span>文章管理</span>
                <el-button type="primary">添加文章</el-button>
            </div>
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="文章分类:">
                    <el-select v-model="formInline.categoryId" placeholder="请选择" clearable
                        :disabled="categoryOptions.length <= 1">
                        <el-option v-for="opt in categoryOptions" :key="opt.value" :label="opt.label"
                            :value="opt.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="发布状态:">
                    <el-select v-model="formInline.stateId" placeholder="请选择" clearable
                        :disabled="stateOptions.length <= 1">
                        <el-option v-for="opt in stateOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
                    </el-select>
                </el-form-item>
                <!-- 未实现时间筛选 -->
                <el-form-item label="发布时间:">
                    <el-date-picker v-model="formInline.date" type="datetime" placeholder="选择日期时间" />
                </el-form-item>
                <el-form-item label="请输入查询关键字:">
                    <el-input v-model="formInline.keyword" placeholder="请输入内容" clearable>
                        <template #prefix>
                            <Search />
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">搜索</el-button>
                    <el-button type="default" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="tableData" style="width: 100%">
                <el-table-column prop="id" label="文章ID" />
                <el-table-column prop="title" label="标题" />
                <el-table-column prop="category.categoryName" label="类别" />
                <el-table-column prop="time" label="发布时间" />
                <el-table-column prop="state.stateName" label="状态" />
                <el-table-column label="操作">
                    <el-row>
                        <el-button type="primary" :icon="Edit" circle />
                        <el-button type="danger" :icon="Delete" circle />
                    </el-row>
                </el-table-column>
            </el-table>
            <el-pagination class="pagination" v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[5, 10, 15, 20]" :size="size" :disabled="disabled" :background="background"
                layout="jumper, total, sizes, prev, pager, next" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>
    </div>
</template>

<style scoped>
    .table-container {
        padding: 20px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        gap: 20px;
        position: fixed;
        inset: 0;
        overflow: auto;
    }

    .demo-form-inline {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 20px;
        align-items: center;
        justify-content: space-between;
        margin: 0 auto;
    }

    .pagination {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }

    .demo-form-inline .el-input {
        --el-input-width: 220px;
    }

    .demo-form-inline .el-select {
        --el-select-width: 220px;
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }
</style>